package com.hu.ta.assignment6.beans;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.hu.ta.assignment6.io.FileEmail;

public class SpamClassifier {
	protected VSMWordList vsm;

	public SpamClassifier(InputStream dataIn) throws IOException {
		vsm = new VSMWordList(dataIn);
	}

	public SpamClassifier() {
		vsm = new VSMWordList();
	}

	public void train(List<FileEmail> spams, List<FileEmail> hams) {
		for (FileEmail e : spams) {
			vsm.incDoc(EmailClass.SPAM);
			for (String word : e.getContent().getWords()) {
				vsm.add(word, EmailClass.SPAM);
			}
		}

		for (FileEmail e : hams) {
			vsm.incDoc(EmailClass.HAM);
			for (String word : e.getContent().getWords()) {
				vsm.add(word, EmailClass.HAM);
			}
		}
	}

	public void serializeTo(FileOutputStream fos) throws IOException {
		vsm.serializeTo(fos);
	}

	public void add(String token, EmailClass typ) {
		vsm.add(token, typ);
	}

	public void classify(ArrayList<FileEmail> emails) {
		for (FileEmail e : emails) {
			e.setClassification(classify(e.getContent()));
		}
	}

	public EmailClass classify(EmailContent content) {
		int spamWeight = 0;
		/*
		 * if (countNumbers(content.getSender()) >= 3) { spamWeight++; }
		 * 
		 * if (content.isAllUpperCase()) { spamWeight++; }
		 * 
		 * if (content.getNumHTMLTags() > 22) { spamWeight++; }
		 * 
		 * if (content.getContent().contains("www")) { spamWeight++; }
		 * 
		 * if (content.getNumPictures() > 1) { spamWeight++; }
		 */

		double probSpam = 0.0;
		double probHam = 0.0;
		for (String word : content.getWords()) {
			probSpam += (vsm.getProbability(word, EmailClass.SPAM));
			probHam += (vsm.getProbability(word, EmailClass.HAM));

			/*
			 * if (word.equals("fat") || word.equals("burner") ||
			 * word.equals("insurance") || word.equals("free") ||
			 * word.equals("gratis") || word.equals("million") ||
			 * word.equals("millions") || word.equals("mio") ||
			 * word.equals("congo") || word.equals("cancer") ||
			 * word.equals("product") || word.equals("natural") ||
			 * word.equals("money") || word.equals("girls") ||
			 * word.equals("bigger") || word.equals("guarantee") ||
			 * word.equals("guarantees") || word.equals("price") ||
			 * word.equals("low") || word.equals("performance") ||
			 * word.contains("$")) { spamWeight++; } if (countNumbers(word) >=
			 * 1) { spamWeight++; }
			 */
		}

		if (probHam <= probSpam) {
			spamWeight++;
		}

		if (spamWeight >= 1) {
			return EmailClass.SPAM;
		} else
			return EmailClass.HAM;
	}

}
